package com.woniu.sharepark.util.websocket;



import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author xin
 * @date 2019/6/14 16:28
 * version v1.0
 */
@ServerEndpoint("/ws/messageServer/{account}")
@Component
public class MsgWebSocketServer {

    private static final  String GROUP_SENT="0";

    private static ConcurrentHashMap<String, MsgWebSocketServer> webSockets=new ConcurrentHashMap<String, MsgWebSocketServer>();

    private Session session;


    @OnOpen
    public void onOpen(Session session,@PathParam("account") String account){
       this.session=session;
       webSockets.put(account,this);

    }


    @OnClose
    public void onClose(@PathParam("account") String account){
       webSockets.remove(account,this);


    }

    @OnMessage
    public void onMessage(String message, Session session,@PathParam("account") String account) {
        //可以自己约定字符串内容，比如 内容|0 表示信息群发，内容|X 表示信息发给账号为X的用户
        String sendMessage = message.split("[|]")[0];
        String sendUserAccount = message.split("[|]")[1];

            if(GROUP_SENT.equals(sendUserAccount)) {
                sendToAll(sendMessage,account);
            } else{
                sendToUser(sendMessage,sendUserAccount,account);
            }


    }

    public static void sendToUser(String message,String sendUserAccount,String account)  {
        if (webSockets.get(sendUserAccount) != null) {
            if(!account.equals(sendUserAccount)) {
                webSockets.get(sendUserAccount).sendMessage("用户" + account + "发来消息：" + " <br/> " + message+"<br>");

            }
        } else {
            //如果用户不在线则返回不在线信息给自己
            sendToUser("当前用户不在线",account,account);
        }
    }


    public static void sendToAll(String message,String account)  {
        for (String key : webSockets.keySet()) {

          if (!key.equals(account)) {
              webSockets.get(key).sendMessage("管理员" + account + "发来消息：" + " <br/> " + message+"<br>");
          }
          }

    }


    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }




}
